#!/usr/bin/python
# -*- coding: utf-8 -*-

#import Header
from fileUploadClass import fileUploadClass
import pymysql
import pymysql.cursors
import logging
import json
import requests
import time
from hashlib import md5
#from pymongo import MongoClient
from helpTool import get_file_md5, get_file_sha_1,get_FileSize
import os


import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#上面三行用来保证把中文存储到数据库中

class IQiYiClass(object):

    __ChannelID = '3' #视频网站渠道号
    # 在开放平台注册的数据，定值
    __clientKey = '19107b6eface4eb98885de6ed8b79dac'
    # 在开放平台注册的数据，定值
    __clientSecret = '5bebfa16349ecdaa269331dff6bd6cf2'

    def __init__(self, uId, videoId):

        logging.debug('IQiYiClass __int__')

        self.uId = uId #用户ID
        self.localDBTableVideoId = videoId #服务器上数据库表中的视频ID

        self.localVideoPath = '' #服务器上的视频路径
        self.accessToken = ''#从数据库中读取的AccessToken
        self.uploadVideoUrl = ''#动态获取的分片文件上传地址
        self.uploadVideoName = ''#获取视频文件名
        self.uploadThumbUrl = ''#视频封面Url
        self.uploadLabel = ''#视频封面标签, 字符串，如果有多个标签，用";"分割，比如"abc;def"
        self.uploadTitle = ''#视频文章标题
        self.uploadSave = ''#1发布文章，0存草稿
        self.articleId = '' #发布成功之后返回来的文章ID
        self.thumbFilePath = '' #专辑图文件在服务器上的存储位置
        self.dbConnect = None
        self.dbCursor = None
        self.refresh_token = ''
        self.file_id = ''
        self.file_name = ''
        self.description = ''
        self.tags = ''
        self.file_type = ''
        self.tv_accountID = ''

        #不需要对数据库句柄做判断，如果连接不上，会抛异常
        self.dbConnect = pymysql.connect('127.0.0.1', 'root', 'KeYpZrZx', 'chuanchuan', charset='utf8')
        self.dbCursor = self.dbConnect.cursor(cursor=pymysql.cursors.DictCursor)

    def __del__(self):
        self.closeDB()

    #从数据库中读取AccessToken 6fea267b383bed8deca0bd1e75bf4935
    def _getAccessTokenFromDB(self):
        logging.debug('_getAccessTokenFromDB')

        sql = 'SELECT id,result FROM `tv_account` WHERE uid = %s AND platform = %s LIMIT 1'
        self.dbCursor.execute(sql, (self.uId, self.__ChannelID))
        result = self.dbCursor.fetchone()
        self.tv_accountID = result['id']
        resultString = result['result']
        logging.debug('resultString = %s', resultString)
        resultDict = json.loads(resultString)
        dataDict = resultDict['data']
        self.accessToken = dataDict['access_token']
        self.refresh_token = dataDict['refresh_token']

    #刷新授权第三方用户的access_token（如果需要）
    def _refreshToken(self):
        logging.debug('_refreshToken')
        params = {'client_id': self.__clientKey,
                  'grant_type': 'refresh_token',
                  'refresh_token': self.refresh_token
                  }

        resData = requests.get('https://openapi.iqiyi.com/api/oauth2/token', params=params)
        logging.debug(resData)
        if resData.status_code == 200:
            if resData.json().get('code') == u'A00000':
                self.accessToken = resData.json().get('data').get('access_token')
                self.refresh_token = resData.json().get('data').get('refresh_token')
                # 必须把refresh_token 写库，下次刷新需要
                #方案就是每次都把json串存回去
                sql = 'UPDATE `tv_account` SET `result`=%s WHERE id = %s'
                self.dbCursor.execute(sql, (resData.text, self.tv_accountID))
                self.dbConnect.commit()
                logging.debug('保存到数据库')

        return 1

    #去获取文件分片上传地址
    def _getChunkUploadInfo(self):
        logging.debug('_getChunkUploadInfo')
        sql = 'SELECT url FROM `tv_video` WHERE id = %s LIMIT 1'
        self.dbCursor.execute(sql, self.localDBTableVideoId)
        result = self.dbCursor.fetchone()

        self.localVideoPath = result['url']
        self.localVideoPath = self.localVideoPath.replace('http://api.chuanchuan.tv/', '/data/wwwroot/apichuanchuantv/public/')

        params = {'access_token': self.accessToken,
                  'filetype': os.path.splitext(self.localVideoPath)[1][1:], #mp4,avi
                  'filesize': os.path.getsize(self.localVideoPath)#因为本身就是utf8
                }

        resData = requests.get('http://upload.iqiyi.com/openupload', params=params)
        logging.debug('resData = %s', resData.text)
        if resData.status_code == 200:
            resJson = resData.json()
            if resJson.get('code') == u'A00000':
                self.file_id = resJson.get('data').get('file_id')
                self.uploadVideoUrl = resJson.get('data').get('upload_url')
                return 0
        return 1

    def read_in_chunks(self, filePath, chunk_size=1024 * 1024):
        file_object = open(filePath)
        while True:
            chunk_data = file_object.read(chunk_size)
            if not chunk_data:
                break
            yield chunk_data

    #开始上传文件
    def _StartUploadFile(self):
        file_size = os.path.getsize(self.localVideoPath)
        chunk_size = 1 * 1024 * 1024  # 每个分片大小，1M（可根据需要自定义分片大小）
        i = 0
        start = 0  # 分片开始位置
        end = 0  # 分片结束文章

        # 2. 分片上传
        for chunk in self.read_in_chunks(self.localVideoPath):
            start = i * chunk_size
            end = start + chunk_size

            if end > file_size:
                end = file_size

            payload = {'file': chunk}
            headers = {'range': '%s-%s' % (start, end - 1),
                       'file_id': self.file_id,
                       'file_size':str(file_size)
                       }

            send_video = requests.post(self.uploadVideoUrl, files=payload, headers=headers)
            logging.debug('send_video.text = %s', send_video.text)
            # logging.debug('status_code = %d, send_video = %s', send_video.status_code, send_video.text)
            if 200 == send_video.status_code:
                if send_video.json().get('code') != u'A00000':
                    return 1
            else:
                return 1
            i = i + 1

        logging('文件上传完成')
        res = requests.post('http://upload.iqiyi.com/uploadfinish', data={'file_id': self.file_id})
        print 'res.text = %s' % res.text
        if 200 == res.status_code:
            if res.json().get('code') == u'A00000':
                logging.debug('确认上传完成')
                return 0
        return 1

    #关闭数据库连接
    def closeDB(self):
        if self.dbCursor:
            self.dbCursor.close()

        if self.dbConnect:
            self.dbConnect.close()

    #发表视频文章接口
    def _newArticlePost(self):
        logging.debug('_newArticlePost')

        sql = 'SELECT title,name,description,tags,sort FROM `tv_release` a LEFT JOIN tv_video b ON a.video_id = b.id WHERE a.uid = %s AND a.video_id = %s AND a.platform = %s LIMIT 1'
        self.dbCursor.execute(sql, (self.uId, self.localDBTableVideoId, self.__ChannelID))
        result = self.dbCursor.fetchone()
        print result

        self.file_name = result['title'] #文件名
        self.tags = result['tags'] #标签
        self.description = result['description'] #描述
        self.file_type = result['sort'] #视频类型

        if (self.file_type is None) or (len(self.file_type) == 0):
            self.file_type = '7'

        params = {'access_token': self.accessToken, #
             'file_id': self.file_id, #文件上传id
             'file_name': self.file_name, #文件名称
             'description': self.description, #文件描述
             'tags': self.tags, #用户自定义标签，如"青春、搞笑"等等 以半角逗号分隔
             'file_type': self.file_type #分类
                  }

        resData = requests.get('http://openapi.iqiyi.com/api/file/info', params=params)
        logging.debug('resData = %s', resData.text)

        if resData.status_code == 200 and len(resData.text):
            if resData.json().get('code') == u'A00000':
                logging.debug('发布视频文章成功')
                return 0#成功返回 0

        logging.debug('发布视频文章失败')
        return 1#失败返回 1

    # #获取视频状态
    # def getVideoStatus(self):
    #
    #     self.accessToken = '2.7e812132e2e9be666e2083075abb5aed'
    #     self.file_id = '7a256f145615454ba2e7d1c4131b8370'
    #
    #     url = 'http://openapi.iqiyi.com/api/file/fullStatus'
    #     params = {'access_token': self.accessToken, 'file_id': self.file_id}
    #     resData = requests.get(url, params=params)
    #     print 'resData = %s' % resData.text
    #
    #     if resData.status_code == 200 and len(resData.text):
    #         if resData.json().get('code') == u'A00000':
    #             logging.debug('视频处理完成')
    #             print '视频处理完成'


    #分发接口 对外只有一个可调用接口
    def distribute(self):
        logging.debug('iqiyi distribute')
        print '爱奇艺分发开始'

        #第一步，从数据库中读取AccessToken
        self._getAccessTokenFromDB()

        #第二步，刷新token
        self._refreshToken()

        #第二步，去获取文件分片上传地址
        ret = self._getChunkUploadInfo()
        if(ret == 1):
            print '获取文件分片上传地址失败'
            logging.debug('获取文件分片上传地址失败')
            return 1

        #第三步，开始上传文件
        ret = self._StartUploadFile()
        if ret == 1:
            print '上传文件出错'
            logging.debug('上传文件出错！')
            return 1

        #第六步，开始发表视频文章
        ret = self._newArticlePost()
        if ret == 0:
            #成功写库
            sql = 'UPDATE `tv_release` SET `status`=2,`update_time`=now() WHERE uid = %s AND platform = %s AND video_id = %s'
            self.dbCursor.execute(sql, (self.uId, self.__ChannelID,self.localDBTableVideoId))  # 渠道为 1
            self.dbConnect.commit()
            print '上传视频文章成功---已写库'
            logging.debug('上传视频文章成功---已写库')
        else:
            #失败写库
            sql = 'UPDATE `tv_release` SET `status`=3,`update_time`=now(),`reason`=%s WHERE uid = %s AND platform = %s AND video_id = %s'
            self.dbCursor.execute(sql, ('内部错误'.encode('UTF-8'), self.uId, self.__ChannelID, self.localDBTableVideoId))
            self.dbConnect.commit()
            print '上传视频文章失败---已写库'
            logging.debug('上传视频文章失败---已写库')
            return 1

        print '爱奇艺渠道分发完成'
        logging.debug('爱奇艺渠道分发完成')
        return 0


# def main():
#     iqiyi = IQiYiClass('','')
#     iqiyi.getVideoStatus()
#
# if __name__ == "__main__":
#     main()